#!/usr/bin/env python
#coding:UTF-8

import redis_connector as redis
import plugin_conf
import threading
import json
import sys, time
import threading

hostname = 'alex_test'

channel = 'baoyj'

def request_configuration(host):
    config_data = redis.r.get('HostConfiguration::%s' % host)
    if config_data is not None:
        config_data = json.loads(config_data)
    else:
        sys.exit('\033[31;1mCould not load the configuration data \
                        from monitor server,please check!\033[0m')
    return config_data

def plugin_publish(plugin_f):

    data = plugin_f()
    status_dic= {'hostname': hostname, 'data': data }
    redis.r.publish(channel, json.dumps(status_dic))

def plugin_run(service_config):
    service_name, interval , plugin_name = service_config
    plugin_func = getattr(plugin_conf, plugin_name)
    res = plugin_func()
    service_client = {'hostname': hostname,
                      'service_name': service_name,
                      'data': res}
    redis.r.publish(channel, json.dumps(service_client))
    print('Service::%s\tData::\n%s\n%s' % (service_name, res, '-'*20))
    return res

configure_data = request_configuration(hostname)


while True:
    for service_name, v in configure_data.items():
        interval, plugin_name, last_run = v
        # check CD
        if (time.time() - last_run) >= interval:
            t = threading.Thread(target=plugin_run, args=(
            (service_name, interval, plugin_name),))
            t.start()
            # update time stamp
            configure_data[service_name][2] = time.time()
        else:
            print("\033[32;1mService %s colds down now\033[0m" % service_name)
    time.sleep(1)  # loop check CD = 1s

#for i in range(2**20):
#    data = range(10)
#    print redis.r.publish(channel, pickle.dumps(data))

